<!-- 登录组件 -->
<template>
	<view class="logon">
		<!-- <view class="logon_img">
			<image src="/static/carousel04.png"></image>
		</view> -->
		<!-- <view class="loginMask"></view> -->
		<view class="login-container">
			<!-- 登录方式切换 -->
			<view class="login-type">
				<text :class="['type-item', activeType === 'sms' ? 'active' : '']"
					@click="switchType('sms')">短信登录</text>
				<text :class="['type-item', activeType === 'pwd' ? 'active' : '']"
					@click="switchType('pwd')">密码登录</text>
			</view>

			<!-- 表单区域 -->
			<view class="form-box">
				<!-- 手机号输入 -->
				<view class="input-group">
					<input type="number" style="font-size:15px;" placeholder="请输入手机号" v-model="formData.mobile" maxlength="11"
						@input="validatePhone" />
					<text class="clear-btn" style="cursor:pointer;" @click="formData.mobile = ''" v-show="formData.mobile">×</text>
				</view>
				<!-- 密码/验证码输入 -->
				<view class="input-group" v-if="activeType === 'sms'">
					<input type="number" placeholder="请输入验证码" v-model="formData.code" maxlength="6" />
					<text class="code-btn" :class="{ disabled: countDown > 0 }" @click="getSmsCode">
						{{ countDown > 0 ? `${countDown}s后重发` : '获取验证码' }}
					</text>
				</view>
				<!--  -->
				<view class="input-group" v-else>
					<input class="uni-input" placeholder="请输入密码" v-model="formData.password" :password="showPassword" />
					<uni-icons class="icons" :type="!showPassword ? 'eye' : 'eye-slash'" size="30"
						@click="changePassword"></uni-icons>
				</view>
				<!-- 登录按钮 -->
				<button class="login-btn" @click="handleLogin">立即登录</button>
				<!-- 协议 -->
				<view class="login-radio">
					<checkbox-group @change="handleCheckboxChange">
						<label>
							<checkbox value="agree" :checked="isChecked" />
						</label>
						<text class="radio_text">我已阅读并同意</text>
						<text class="radio_text radio_link" @click="openPopup" style="cursor:pointer;">《工术光电用户服务协议和隐私政策》</text>
					</checkbox-group>
				</view>
			</view>
		</view>
		<popup @popupAgreed="agreedFun" :isAgreed="isAgreed"></popup>
	</view>
</template>

<script>
	var login = uniCloud.importObject('login',{customUI:true});
	export default {
		name: "logon",
		data() {
			return {
				mobile:'',
				code:'',
				activeType: 'sms', // 当前登录类型
				formData: {
					mobile: '',
					password: '',
					code: ''
				},
				showPwd: false, // 密码可见性
				countDown: 0, // 验证码倒计时
				timer: null, // 定时器
				showPassword: true,
				isChecked: true, // 初始未选中
				isAgreed: false // 协议弹窗
			};
		},
		computed: {},
		methods: {
			agreedFun(val) {
				if (val === "closePopup") {
					this.isAgreed = false;
				} else if (val === "handleAgree") { // 同意并继续
					this.isAgreed = false;
					this.isChecked = true;
				}
			},
			openPopup() {
				this.isAgreed = true;
			},
			handleCheckboxChange(e) {
				this.isChecked = e.detail.value.includes('agree');
				// 其他业务逻辑处理
			},
			// 切换登录方式
			switchType(type) {
				this.activeType = type
				this.formData = {
					mobile: this.formData.mobile,
					password: '',
					code: ''
				}
			},

			// 校验手机号格式
			validatePhone() {
				this.formData.mobile = this.formData.mobile.replace(/[^\d]/g, '')
			},
			//生成六位随机数
			getSixDigitRandom() {
			    // 生成100000到999999之间的随机整数
			    // Math.random()生成0-1之间的随机数
			    // 乘以900000得到0-900000之间的数
			    // 加上100000确保最小值为100000
			    // Math.floor()取整数部分
			    return Math.floor(Math.random() * 900000) + 100000;
			},
			// 获取短信验证码
			getSmsCode() {
				if(this.countDown > 0){
					return false;
				}
				if (!/^1[3-9]\d{9}$/.test(this.formData.mobile)) {
					uni.showToast({
						title: '请输入正确手机号码',
						icon: 'none'
					})
					
					return;
				}
					
					var code = this.getSixDigitRandom();
					login.sendSms(this.formData.mobile,code).then(res=>{
							if(res.code == 0 && res.success == true){
								//把手机号码和验证码都存到本地,防止发送完后被篡改
								this.mobile = this.formData.mobile;
								this.code = code;
								this.startCountDown();
								uni.showToast({
									title: '发送成功',
									icon: 'none'
								})
							}else{
								uni.showToast({
									title: '发送频繁，请稍后再试',
									icon: 'none'
								})
							}
						
					}).catch(err=>{
						uni.showToast({
							title: '发送频繁，请稍后再试',
							icon: 'none'
						})
					});

				
			},

			// 启动倒计时
			startCountDown() {
				this.countDown = 60
				this.timer = setInterval(() => {
					if (this.countDown <= 0) {
						clearInterval(this.timer)
						return
					}
					this.countDown--
				}, 1000)
			},
			isValidPhoneNumber(phoneNumber) {
				const regex = /^1[3-9]\d{9}$/;
				return regex.test(phoneNumber);
			},
			//获取登录用户信息
			getUserinfo(mobile){
				login.getUserinfo(mobile).then(res=>{
					if(res.code == 200){
						var data = res.result;
						uni.setStorage({
							key: 'login-userinfo',
							data: data,
							success: function () {
								//判断信息是否完善，不完善且为第一次登录，跳转到完善信息页面
								if(!data.login_number || data.login_number == 0){
									//跳转到完善资料页面
									uni.navigateTo({
										url: '/pages/dersonalCenter/dersonalCenter'
									});
								}else{
									const pages = getCurrentPages();
									  // 如果有上一页，后退再前进
									  if (pages.length > 1) {
									        // 后退后再重新进入当前页
									        uni.navigateTo({
									          url: '/' + pages[pages.length - 2].route
									        });
									    
									  } else {
									    // 没有上一页时直接重新加载
									    uni.reLaunch({
									      url: '/pages/index/index'
									    });
									  }
								}
								
								
							}
						});
					}
					
				});
			},
			// 执行登录操作
			async handleLogin() {
				if(this.isChecked == false){
					uni.showToast({
						title:'请先阅读并同意用户服务协议',
						icon:'none'
					})
					return false;
				}
				var mobile = this.mobile;
				var formDataMobile = this.formData.mobile;
				
				if (this.isValidPhoneNumber(this.formData.mobile) == false) {
					uni.showToast({
						title:'手机号码格式不正确',
						icon:'none'
					})
					return false;
				} 
				if (this.activeType === 'pwd') {
					var password = this.formData.password;
					if(!password){
						uni.showToast({
							title:'请输入密码',
							icon:'none',
							duration:2000
						})
						return
					}
					uni.showLoading({
						title:'登录中'
					})
					login.login(formDataMobile,this.formData.password).then(res=>{
						if(res.code == 200){
							uni.hideLoading()
							//再次查询出用户信息并缓存
							this.getUserinfo(formDataMobile);
							uni.showToast({
								title:'登录成功',
								icon:'none',
								duration:2000
							})
							
						}else{
							uni.hideLoading()
							uni.showToast({
								title:res.message,
								icon:'none',
								duration:2000
							})
						}
					})
					
				} else {
					if(!mobile){
						uni.showToast({
							title:'请先获取验证码',
							icon:'none'
						})
						return false;
					}
					//验证手机号码是否被篡改
					if(formDataMobile!=mobile){
						uni.showToast({
							title:'手机号码已变更，请重新获取验证码',
							icon:'none'
						})
						return false;
					}
					uni.showLoading({
						title:'登录中'
					})
					if(this.formData.code != this.code){
						uni.showToast({
							title:'验证码错误',
							icon:'none'
						})
						return false;
					}else{
						//执行登录或注册操作
						this.login(formDataMobile);
					}
				}
				
			},
			//登录或注册
			login(mobile,password = null){
				login.login(mobile).then(res=>{
					if(res.code == 200){
						uni.hideLoading()
						//再次查询出用户信息并缓存
						this.getUserinfo(mobile);
						uni.showToast({
							title:'登录成功',
							icon:'none',
							duration:2000
						})
					}
				});
			},
			changePassword: function() {
				this.showPassword = !this.showPassword;
			}
		},
		beforeDestroy() {
			clearInterval(this.timer)
		}
	}
</script>

<style scoped>
	
	.logon {
		width: 100%;
		min-width: 1360px;
		box-sizing: border-box;
		height: calc(100% - 90px);
		background-color: #d9001b;
		display: flex;
		/* background: url(/static/logoback.png) 100% 100% no-repeat; */
		background: url(/static/logoin.png) no-repeat;
		background-size: cover;
		background-position: center center;
		overflow: hidden;
		position: relative;
		top: 0;
		left: 0;
	}

	/* .loginMask {
		position: absolute;
		width: 100%;
		min-width: 1360px;
		box-sizing: border-box;
		height: 100%;
		background-color: rgba(217,0,27, 0.1);
		z-index: 1;
	} */

	/* .logon_img {
		flex: 4;
		height: 100%;

	}

	.logon_img image {
		width: 100%;
		height: 100%;
	} */

	.login-container {
		padding: 60px 80px;
		/* flex: 1; */
		width: 480px;
		/* height: 70%; */
		/* float: right; */
		/* margin: auto; */
		background-color: #FFF;
		position: absolute;
		right: 120px;
		/* top: 15%; */
		top: 50%;
		transform: translateY(-50%);
		border-radius: 10px;
		z-index: 2;
		box-sizing: border-box;
	}

	.login-type {
		display: flex;
		margin-bottom: 40px;
	}

	.type-item {
		flex: 1;
		text-align: center;
		font-size: 15px;
		color: #666;
		padding: 20px 0;
		border-bottom: 3px solid transparent;
		cursor: pointer;
	}

	.type-item.active {
		color: #d9001b;
		border-color: #d9001b;
	}

	.input-group {
		position: relative;
		margin-bottom: 20px;
		border-bottom: 1px solid #eee;
	}

	.input-group input {
		height: 50px;
		font-size: 16px;
		padding-right: 150px;
	}

	.input-group .clear-btn,
	.input-group .eye-icon,
	.input-group .code-btn {
		position: absolute;
		right: 20px;
		top: 50%;
		transform: translateY(-50%);
		font-size: 30px;
		color: #999;
	}

	.input-group .code-btn {
		font-size: 14px;
		color: #d9001b;
		cursor: pointer;
	}

	.input-group .code-btn.disabled {
		color: #ccc;
	}

	.icons {
		position: absolute;
		top: 15px;
		right: 0;
		font-size: 20px !important;
		cursor: pointer;
	}

	.login-btn {
		margin-top: 100px;
		background: #d9001b;
		color: #fff;
		border-radius: 20px;
		font-size: 15px;
		height: 40px;
	}

	.login-btn[disabled] {
		background: #ccc;
	}

	.login-radio {
		margin-top: 30px;
	}

	.login-radio /deep/ .uni-checkbox-input {
		width: 16px;
		height: 16px;
		margin-right: 3px;
		border-radius: 9px;
	}

	.login-radio /deep/ .uni-checkbox-input:hover {
		border-color: var(--HOVER-BD-COLOR, #d9001b) !important;
		;
	}

	.login-radio /deep/ .uni-checkbox-input svg path {
		fill: #d9001b;
	}

	.radio_text {
		font-size: 12px;
	}

	.radio_link {
		color: #0563C1;
		text-decoration: underline;
	}
</style>